package cn.stylefeng.guns.utils.word;

import cn.stylefeng.guns.modular.wms.model.result.EduExpResult;
import cn.stylefeng.guns.modular.wms.model.result.ProExpResult;
import cn.stylefeng.guns.modular.wms.model.result.ResumeResult;
import cn.stylefeng.guns.modular.wms.model.result.WorkExpResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * freemarker 根据模板生成word
 */
public class TestResumeUtil {

    // ftl模板目录
    private String ftlUrl = "F:/";
    // ftl模板名称
    private String ftlName = "resume.ftl";
    // 输出doc文件目录
    private String outUrl = "F:/";
    // 输出文件名称
    private String outFileName = "resume.doc";

    /**
     * 获取word填充数据
     *
     * @param resumeVo
     * @return
     */
    private static Map<String, Object> getData(ResumeResult resumeVo) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", resumeVo.getName());
        map.put("sex", resumeVo.getSex()==1?"男":"女");
        map.put("birthday", resumeVo.getBirthday());
        map.put("phone", resumeVo.getPhone());
        map.put("email", resumeVo.getPhone());
        map.put("timeToWork",resumeVo.getTimeToWork());
        map.put("workYear",resumeVo.getWorkYear());
        map.put("education", resumeVo.getEducation());
        map.put("avatar", resumeVo.getAvatar());
        map.put("address", resumeVo.getAddress());
        map.put("personalSkill",resumeVo.getPersonalSkill());
        map.put("eduExpList", resumeVo.getEduExpList());
        map.put("workExpList", resumeVo.getWorkExpList());
        map.put("proExpList", resumeVo.getProExpList());
        return map;
    }

    /**
     * 根据模板生成word
     */
    public void beanToWord(ResumeResult culturalActivity) throws IOException, TemplateException {
        Map<String, Object> map = getData(culturalActivity);
        //Configuration用于读取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        /*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是
         * 指定ftl文件所在目录的路径,而不是ftl文件的路径
         */
        //指定路径的第一种方式(根据某个类的相对路径指定)
//        configuration.setClassForTemplateLoading(this.getClass(),"/template");
        //指定路径的第二种方式,我的路径是C:/a.ftl
        configuration.setDirectoryForTemplateLoading(new File(ftlUrl));

        String outFileUrl = outUrl + "/" + outFileName;
        // 输出文档路径及名称
        File outFile = new File(outFileUrl);

        //以utf-8的编码读取ftl文件
        Template template =  configuration.getTemplate(ftlName,"utf-8");

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
        template.process(map, out);
        out.close();
        System.out.println(outFileUrl);
    }

    public static void main(String[] args) {
        ResumeResult resumeResult = new ResumeResult();
        resumeResult.setName("易先生");
        resumeResult.setSex(1);
        resumeResult.setBirthday("2022-05-25");
        resumeResult.setPhone("199999999991");
        resumeResult.setEducation("本科");
        resumeResult.setWorkYear("3");
        resumeResult.setTimeToWork("2019-07");
        resumeResult.setAddress("地址");
        resumeResult.setAvatar(ImageBase64("https://bendao.oss-cn-shenzhen.aliyuncs.com/job/user/165201942824864.png"));
        resumeResult.setPersonalSkill("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

        List<EduExpResult> eduExpList=new ArrayList<>();
        EduExpResult eduExp=new EduExpResult();
        eduExp.setSchool("清华大学");
        eduExp.setStartTime("2021-07");
        eduExp.setEndTime("2022-07");
        eduExp.setMajor("计算机科学与技术");
        eduExp.setEducation("本科");
        eduExpList.add(eduExp);

        eduExp=new EduExpResult();
        eduExp.setSchool("清华大学");
        eduExp.setStartTime("2021-07");
        eduExp.setEndTime("2022-07");
        eduExp.setMajor("计算机科学与技术");
        eduExp.setEducation("本科");
        eduExpList.add(eduExp);

        List<ProExpResult> proExpList=new ArrayList<>();
        ProExpResult proExp=new ProExpResult();
        proExp.setName("同城配送应用开发");
        proExp.setStartDate("2022-05");
        proExp.setEndDate("2022-06");
        proExp.setDescr("同城配送同城配送");
        proExp.setRole("项目经理");
        proExp.setPerformance("无");
        proExpList.add(proExp);

        proExp=new ProExpResult();
        proExp.setName("同城配送应用开发");
        proExp.setStartDate("2022-05");
        proExp.setEndDate("2022-06");
        proExp.setDescr("同城配送同城配送");
        proExp.setRole("项目经理");
        proExp.setPerformance("无");
        proExpList.add(proExp);

        List<WorkExpResult> workExpList=new ArrayList<>();
        WorkExpResult workExp=new WorkExpResult();
        workExp.setCompanyName("晴空蓝网络科技");
        workExp.setStartDate("2022-05");
        workExp.setEndDate("2022-06");
        workExp.setDepartment("技术部");
        workExp.setJobContent("工作内容工作内容");
        workExp.setPostName("项目经理");
        workExpList.add(workExp);

        workExp=new WorkExpResult();
        workExp.setCompanyName("晴空蓝网络科技");
        workExp.setStartDate("2022-05");
        workExp.setEndDate("2022-06");
        workExp.setDepartment("技术部");
        workExp.setJobContent("工作内容工作内容");
        workExp.setPostName("项目经理");
        workExpList.add(workExp);

        resumeResult.setEduExpList(eduExpList);
        resumeResult.setProExpList(proExpList);
        resumeResult.setWorkExpList(workExpList);
        try {
            TestResumeUtil wordUtil = new TestResumeUtil();
            wordUtil.beanToWord(resumeResult);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        System.out.println("好了");
    }


    /**
     *
     * 远程读取image转换为Base64字符串
     * @param imgUrl
     * @return
     */
    public static  String ImageBase64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();

            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return new BASE64Encoder().encode(outStream.toByteArray());
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            if(is != null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outStream != null)
            {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpUrl != null)
            {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }
}